
<template>
    <div class="divAddGoodsDetail box divWarehouse">
        <div class="tableInfo">
            <base-button
            class="importantButton"
            @click="dialogData.visible = true"
            >添加货品</base-button>
            <base-button
            class="unimportanceButton"
            @click="btnBatchDeleteClick"
            >删除货品</base-button>
        </div>
        <div class="divTableTitle" v-if="tableTitle.checkedArr.length > 0">
            <span class="divLabel">总计：</span><span class="spanValue">{{tableTitle.sumNum}}件</span>
            <span class="divLabel">总体积：</span><span class="spanValue">{{tableTitle.sumVolume}}m³</span>
        </div>
        <div  v-if="tableData.length>0">
            <el-table
            :data="tableData"
            stripe
            border
            style="width: 100%"
            v-loading="loading"
            ref="multipleTable"
            :header-cell-style="{ background: '#f9f6ee' }"
            @selection-change="handleSelectionChange"
            >
                <el-table-column
                    type="selection"
                    align="center"
                    width="55">
                </el-table-column>
                <el-table-column
                    type="index"
                    align="center"
                    width="68"
                    label="序号"
                />
                <el-table-column
                    prop="ownerName"
                    align="center"
                    label="货主名称"
                    width="160"
                />
                <el-table-column
                    prop="goodsCode"
                    align="center"
                    label="货品编号"
                    width="150"
                />
                <el-table-column
                    prop="goodsName"
                    align="center"
                    label="货品名称"
                    width="160"
                >
                </el-table-column>
                <el-table-column
                    prop="goodsTypeName"
                    align="center"
                    label="货品类型"
                    width="160"
                />
                <el-table-column
                    prop="goodsPrice"
                    align="center"
                    label="货品单价(元)"
                    width="160"
                />
                <el-table-column
                    prop="goodsGuaranteeDay"
                    align="center"
                    label="保质天数(天)"
                    width="160"
                >
                </el-table-column>
                <el-table-column
                    prop="goodsUnit"
                    align="center"
                    label="单位"
                    width="160"
                >
                </el-table-column>
                <el-table-column
                    prop="goodsVolume"
                    align="center"
                    label="体积(m³)"
                    width="160"
                >
                </el-table-column>
                <el-table-column
                    prop="planNum"
                    align="center"
                    label="到货数量"
                    width="160"
                >
                  <template slot-scope="{ row }">
                    <span v-if="!row.edit"><span>{{row.planNum}}</span></span>
                    <el-input
                      v-else
                      v-model="row.planNum"
                      class="editInput"
                    ></el-input>
                    <span>
                      <span
                        v-if="!row.edit"
                        class="imagesIcon imgEdit"
                        @click="row.edit = true"
                      ></span>
                      <span
                        v-if="row.edit"
                        class="imagesIcon imgSave"
                        @click="inputSureClick(row)"
                      ></span>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="100" fixed="right">
                    <template slot-scope="{row}">
                    <base-button class="fontOperateButton"  @click="btnDeleteClick([row.id])">删除</base-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <base-pagination :total="paging.total" :limit="paging.size" @current-change="handleCurrentChange"  @size-change="handleSizeChange"></base-pagination>
            <base-dialog    :title="delDialogData.title"
                            :visible="delDialogData.visible"
                            :msg="delDialogData.msg"
                            @btn-cancle-click="delDialogData.visible= false"
                            @btn-sure-click ="btnDeleteSureClick"
            ></base-dialog>
        </div>
        <div class="divDialog">
            <el-dialog :title="dialogData.title" :visible.sync="dialogData.visible">
                <div class="divDialogHead">
                    <el-form
                        ref="ruleForm"
                        :inline="true"
                        :model="dialogData.params"
                    >
                        <el-row :gutter="30">
                            <el-col :span="12">
                                <div class="divLable">货品</div>
                                <el-input
                                placeholder="请输入名称/编码/条码"
                                v-model="dialogData.params.goods"
                                clearable
                                />
                            </el-col>
                            <el-col :span="12">
                                <div class="textRight" style="margin-top: 25px;">
                                <base-button
                                    class="minorImportantButton btnCancle"
                                    @click="btnSearchClick"
                                >查询</base-button>
                                <base-button class="unimportanceButton" @click="btnResetClick">重置</base-button>
                                </div>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="divTableTitle" v-if="dialogData.checkedArr.length > 0">
                    <span class="spanLabel">当前已选</span><span class="spanValue">{{dialogData.checkedNum}}个货品</span>
                </div>
                <el-table
                    :data="dialogData.tableData"
                    stripe
                    border
                    style="width: 100%"
                    ref="dialogTable"
                    v-loading="loading"
                    :header-cell-style="{ background: '#f9f6ee' }"
                    @selection-change="dialogHandleSelectionChange"
                >
                    <el-table-column
                        type="selection"
                        align="center"
                        width="55"
                        :selectable="selectEnable"
                    />
                    <el-table-column
                        type="index"
                        align="center"
                        width="68"
                        label="序号"
                    />
                    <el-table-column
                        prop="ownerName"
                        align="center"
                        label="货主名称"
                        width="160"
                    />
                    <el-table-column
                        prop="code"
                        align="center"
                        label="货品编码"
                        width="150"
                    />
                    <el-table-column
                        prop="name"
                        align="center"
                        label="货品名称"
                        width="160"
                    />
                    <el-table-column
                        prop="goodsTypeName"
                        align="center"
                        label="货品类型"
                        width="160"
                    />
                    <el-table-column
                        prop="price"
                        align="center"
                        label="货品单价(天)"
                        width="150"
                    />
                    <el-table-column
                        prop="guaranteeDay"
                        align="center"
                        label="保质天数(天)"
                        width="160"
                    />
                    <el-table-column
                        prop="unit"
                        align="center"
                        label="单位"
                        width="150"
                    />
                    <el-table-column
                        prop="volume"
                        align="center"
                        label="体积(m³)"
                        width="160"
                    />
                </el-table>
                <base-pagination :total="dialogData.paging.total" :limit="dialogData.paging.size" @current-change="handleDialogCurrentChange"  @size-change="handleDialogSizeChange"></base-pagination>
                <span slot="footer" class="dialog-footer">
                    <base-button  @click="dialogData.visible = false" class="unimportanceButton" style="margin-right:20px">取消</base-button>
                    <base-button @click="btnSureAddClick" class="minorImportantButton" >确认添加</base-button>
                </span>
            </el-dialog>
        </div>
        <div class="buttonBox" style="padding-bottom:25px;margin-left:0;margin-right:0">
          <base-button
            class="unimportanceButton"
            @click="btnReturnClick"
          >返回</base-button>
          <base-button
            class="minorImportantButton"
            @click="btnNextStepClick"
          >提交</base-button>
        </div>
    </div>
</template>
<script lang="ts">
import SinglePage from '@/mixin/single-page'
import { mixins } from 'vue-class-component'
import { Component, Prop } from 'vue-property-decorator'
import BaseButton from '@/components/base-button/index.vue'
import BasePagination from '@/components/base-pagination/index.vue'
import { IWarehouseInListTableData } from '@/module-storage-in/interface/warehouse-in-list'
import { batchAddWarehouseInList, deleteWarehouseInList, findWarehouseInListDetailPaging, updateWarehouseInList, findSelectedWarehouseInList, deleteWarehouseInListByMasterId } from '@/module-storage-in/api/warehouse-in-list'
import { GoodsTabaleData } from '@/module-base/interface/goods'
import { getGoodsList } from '@/module-base/api/goods'
import { ICommonReturn } from '@/utils/common-interface'
import BaseDialog from '@/components/base-dialog/index.vue'

@Component({
  name: 'ComponentAddGoodsDetail',
  components: {
    BaseButton,
    BasePagination,
    BaseDialog
  }
})
// 需要混入,因为返回的时候需要
export default class extends mixins(SinglePage) {
    @Prop({ default: null }) private masterId!: string
    @Prop({ default: null }) private ownerId!: string

    private loading = false;

    private paging = {
      current: 1, // 当前页码
      size: 10, // 每页数据量
      total: 0
    }

    private tableData:IWarehouseInListTableData[] = []

    private tableTitle={
      sumNum: 0, // 总计多少件
      sumVolume: 0, // 总计多少体积
      checkedArr: [] as IWarehouseInListTableData[]
    }

    private dialogData = {
      paging: {
        current: 1, // 当前页码
        size: 10, // 每页数据量
        total: 0
      },
      params: {
        goods: '' // 货品名称/编码/条码
      },
      tableData: [] as GoodsTabaleData[],
      visible: false,
      title: '新增入库货品',
      checkedArr: [] as number[],
      checkedNum: 0,
      selectedIds: [] as number[]
    }

    // 删除弹出框
    private delDialogData = {
      title: '确认删除',
      visible: false,
      msg: '',
      ids: [] as number[]
    }

    created() {
      this.initData()
    }

    private initData() {
      new Promise((resolve) => {
        this.deleteList(resolve)
      }).then(() => {
        this.getList()
        this.getDialogList()
        this.getSelectedGoods()
      })
    }

    private async deleteList(resolve:Function) {
      const parent = (this.$parent as any)
      const map:Map<string, string> = parent.map
      if (map.size > 1) {
        await deleteWarehouseInListByMasterId({ masterId: this.masterId })
        map.clear()
        map.set(this.ownerId, this.ownerId)
        parent.map = map
      }
      resolve()
    }

    private async getSelectedGoods() {
      const { data } = await findSelectedWarehouseInList({ masterId: this.masterId })
      this.dialogData.selectedIds = data
    }

    private async getList() {
      const { data } = await findWarehouseInListDetailPaging({ current: this.paging.current, size: this.paging.size, masterId: this.masterId })
      this.loading = false
      this.tableData = data.records.map((item:IWarehouseInListTableData) => {
        return { ...item, edit: false }
      })
      this.paging.total = parseInt(data.total, 10)
    }

    private handleCurrentChange(page:number) {
      this.paging.current = page
      this.getList()
    }

    private handleSizeChange(page:number) {
      this.paging.size = page
      this.paging.current = 1
      this.getList()
    }

    private async getDialogList() {
      const current = this.dialogData.paging.current
      const size = this.dialogData.paging.size
      const params = {
        ...this.dialogData.params,
        current,
        size,
        ownerId: this.ownerId
      }
      const { data } = await getGoodsList(params)
      // const data = { records: [{ id: '703345', createTime: '2021-05-13 22:20:31', createUser: '11', updateTime: '2021-05-17 11:56:57', updateUser: '11', goodsTypeId: '1', code: 'DAS', name: '123', barCode: '123', ownerId: '2', inspectionType: '1', temperatureType: '1', bearingType: '1', volume: '1', warehouseId: null, areaId: '12', price: '12312', unit: '1', guaranteeDay: 0, status: 0, remark: '', createName: '12433', updateName: '张三', logicDel: 0, ownerName: 'AAAAdad ', ownerCode: '1', goodsTypeName: '1', areaName: '1' }, { id: '125721', createTime: '2021-05-13 22:19:45', createUser: '11', updateTime: '2021-05-17 11:56:57', updateUser: '11', goodsTypeId: '1', code: 'ASD', name: ' 手机', barCode: 's', ownerId: '2', inspectionType: '1', temperatureType: '1', bearingType: '1', volume: '1', warehouseId: null, areaId: '12', price: '12312', unit: '台', guaranteeDay: 10, status: 0, remark: '', createName: '312', updateName: '张三', logicDel: 0, ownerName: 'kent', ownerCode: '1', goodsTypeName: '1', areaName: '1' }, { id: '21001', createTime: '2021-05-13 22:19:31', createUser: '11', updateTime: '2021-05-17 11:56:57', updateUser: '11', goodsTypeId: '1', code: 'ADAS', name: '3312', barCode: '123', ownerId: '2', inspectionType: '1', temperatureType: '1', bearingType: '1', volume: '1', warehouseId: null, areaId: '12', price: '12312', unit: '1', guaranteeDay: 0, status: 0, remark: '', createName: '421', updateName: '张三', logicDel: 0, ownerName: '哒哒da哒', ownerCode: '1', goodsTypeName: '1', areaName: '1' }, { id: '592940', createTime: '2021-05-13 16:40:20', createUser: '11', updateTime: '2021-05-17 11:56:57', updateUser: '11', goodsTypeId: '1', code: 'ASDAS', name: '电视', barCode: '123', ownerId: '2', inspectionType: '1', temperatureType: '1', bearingType: '1', volume: '1', warehouseId: null, areaId: '12', price: '12312', unit: '1', guaranteeDay: 0, status: 0, remark: '', createName: '1321', updateName: '张三', logicDel: 0, ownerName: '哒哒da', ownerCode: '1', goodsTypeName: '1', areaName: '1' }], total: '4', size: '10', current: '1', orders: [] } as any

      this.dialogData.tableData = data.records
      this.dialogData.paging.total = parseInt(data.total, 10)
    }

    private handleDialogCurrentChange(page:number) {
      this.dialogData.paging.current = page
      this.getDialogList()
    }

    private handleDialogSizeChange(page:number) {
      this.dialogData.paging.size = page
      this.dialogData.paging.current = 1
      this.getDialogList()
    }

    private handleSelectionChange(itemList:IWarehouseInListTableData[]) {
      this.tableTitle.checkedArr = itemList
      this.getTableTitleData()
    }

    private dialogHandleSelectionChange(itemList:GoodsTabaleData[]) {
      const idList = itemList.map((item:GoodsTabaleData) => {
        return item.id
      })
      this.dialogData.checkedArr = idList
      this.dialogData.checkedNum = idList.length
    }

    private btnSearchClick() {
      this.getDialogList()
    }

    private btnResetClick() {
      this.dialogData.params = {
        goods: '' // 货品名称/编码/条码
      }
      this.getDialogList()
    }

    // 确认添加
    private async btnSureAddClick() {
      const idList:number[] = this.dialogData.checkedArr
      if (idList.length === 0) {
        this.$message.error('请勾选商品')
      } else {
        const data = ((await batchAddWarehouseInList({
          goodsIds: idList,
          masterId: this.masterId
        })) as unknown) as ICommonReturn
        if (data.code === 0) {
          this.$message.success(idList.length + '条添加成功')
          this.dialogData.visible = false
          this.getList()
          this.getSelectedGoods();
          (this.$refs.dialogTable as any).clearSelection()
        } else {
          this.$message.error(data.msg)
        }
      }
    }

    private async inputSureClick(row:any) {
      if (row.planNum || row.planNum === 0) {
        const data = ((await updateWarehouseInList({ id: row.id, planNum: row.planNum })) as unknown) as ICommonReturn
        if (data.code === 0) {
          this.$message.success('修改成功')
          row.edit = false
          // 进行总计数量的整理
          const checkedArr = this.tableTitle.checkedArr
          let flag = false
          this.tableTitle.checkedArr = checkedArr.map((item:IWarehouseInListTableData) => {
            if (item.id === row.id) {
              item.planNum = row.planNum
              flag = true
            }
            return item
          })
          if (flag) {
            this.getTableTitleData()
          }
        } else {
          this.$message.error(data.msg)
        }
      } else {
        this.$message.error('请输入到货数量')
      }
    }

    private btnBatchDeleteClick() {
      if (this.confirmMsg()) {
        return
      }
      const checkedArr = this.tableTitle.checkedArr
      if (checkedArr.length === 0) {
        this.$message.error('请选择货品')
      } else {
        this.delDialogData.ids = checkedArr.map((item:IWarehouseInListTableData) => {
          return item.id
        })
        this.delDialogData.visible = true
        this.delDialogData.msg = '确定要删除这' + checkedArr.length + '项货品吗？'
      }
    }

    private btnDeleteClick(ids:[]) {
      if (this.confirmMsg()) {
        return
      }
      this.delDialogData.ids = ids
      this.delDialogData.visible = true
      this.delDialogData.msg = '确定要删除这' + ids.length + '项货品吗？'
    }

    private async btnDeleteSureClick() {
      const ids = this.delDialogData.ids
      const data = ((await deleteWarehouseInList({ ids: ids })) as unknown) as ICommonReturn
      if (data.code === 0) {
        this.$message.success('删除成功')
        this.delDialogData.visible = false
        this.getList()
        this.getSelectedGoods()
        const checkedArr = this.tableTitle.checkedArr
        if (checkedArr.length === ids.length) {
          this.tableTitle.checkedArr = []
        } else {
          this.tableTitle.checkedArr = checkedArr.filter(x => ids.find(y => x.id !== y))
          this.getTableTitleData()
        }
        this.delDialogData.ids = []
      } else {
        this.$message.error(data.msg)
      }
    }

    private getTableTitleData() {
      let sumNum = 0
      let sumVolume = 0
      this.tableTitle.checkedArr.forEach((item:IWarehouseInListTableData) => {
        sumNum += item.planNum
        sumVolume += Number(item.goodsVolume)
      })
      this.tableTitle.sumNum = sumNum
      this.tableTitle.sumVolume = sumVolume
    }

    private selectEnable(row:IWarehouseInListTableData) {
      let flag = true
      this.dialogData.selectedIds.forEach(item => {
        if (item === row.id) {
          flag = false
        }
      })
      return flag
    }

    private btnReturnClick() {
      (this.$parent as any).activeStep = 0
    }

    private btnNextStepClick() {
      // 进行是否有编辑状态数据的校验
      let flag = true
      this.tableData.forEach((item :any) => {
        if (item.edit || item.planNum === null || item.planNum === undefined) {
          flag = false
        }
      })

      if (flag) {
        (this.$parent as any).activeStep = 2
        this.closeWindow()
      } else {
        this.$message.error('任务有未填写项，不能完成')
      }
    }
}
</script>
<style lang="scss">
.divAddGoodsDetail{
    .el-table tbody tr:hover>td { background-color: #FFFFFF !important }
    .edit-input{
        .el-input__inner{
            height: 20px;
            line-height: 20px;
        }
    }

}
</style>
<style lang="scss" scoped>
.divAddGoodsDetail{
    .input-img-sure{
        width: 20px;
        height: 20px;
        margin-left: 10px;
        cursor: pointer;
        position: absolute;
        top: 50%;
        right: 10px;
        transform: translate(0, -50%);
    }
    .input-img-edit{
        width: 20px;
        height: 20px;
        cursor: pointer;
        float: right;
    }
    .edit-input{
        width: 80px;
        height: 20px;
    }
    .divTableTitle{
      margin-bottom: 20px;
      background: #FFF9EB;
      border: 1px solid #FFB200;
      height: 32px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      line-height: 32px;
      padding-left: 9px;
      width: fit-content;
      .spanLabel{
        color: #332929;
        margin-right: 9px;
      }
      .spanValue{
        padding-right: 18px;
        color: #FFB200;
      }
    }

    .divDialog{
        .divDialogHead{
            margin-bottom: 20px;
            .divLable{
                padding-bottom: 10px;
            }
        }
    }
}
</style>
